
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using Apps.Models;
using Apps.Common;
using Microsoft.Practices.Unity;
using System.Transactions;
using Apps.BLL.Core;
using Apps.Locale;
using LinqToExcel;
using System.IO;
using System.Text;
using System.Linq.Expressions;
using Apps.IDAL.RC;
using Apps.Models.RC;
using Apps.IBLL.RC;
using System.Data;
using System.Data.Common;
using Oracle.ManagedDataAccess.Client;

namespace Apps.BLL.RC
{
	public partial class RC_PROCESSBLL: Virtual_RC_PROCESSBLL,IRC_PROCESSBLL
	{
        

	}
	public class Virtual_RC_PROCESSBLL
	{
        [Dependency]
        public IRC_PROCESSRepository m_Rep { get; set; }

		public virtual List<RC_PROCESSModel> GetList(ref GridPager pager, string queryStr)
        {

            IQueryable<RC_PROCESS> queryData = null;
            if (!string.IsNullOrWhiteSpace(queryStr))
            {
                queryData = m_Rep.GetList(
								a=>a.PROCESS_ID.Contains(queryStr)
								|| a.DETAIL_ID.Contains(queryStr)
								|| a.CAR_ID.Contains(queryStr)
								|| a.MINE_ID.Contains(queryStr)
								|| a.MATERIEL_ID.Contains(queryStr)
								|| a.SUPPLIER_ID.Contains(queryStr)
								|| a.TRANSPORT_ID.Contains(queryStr)
								
								
								
								);
            }
            else
            {
                queryData = m_Rep.GetList();
            }
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }
		 
		public virtual List<RC_PROCESSModel> GetPagerList(ref GridPager pager, Expression<Func<RC_PROCESS, bool>> whereLambda )
        {

            IQueryable<RC_PROCESS> queryData = m_Rep.GetList(whereLambda); 
             
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }

		public virtual List<RC_PROCESSModel> GetList(Expression<Func<RC_PROCESS, bool>> whereLambda )
        {

            IQueryable<RC_PROCESS> queryData = m_Rep.GetList(whereLambda); 
       
            return CreateModelList(ref queryData);
        }

		public virtual List<RC_PROCESSModel> GetListByParentId(ref GridPager pager, string queryStr,object parentId)
        {
			return new List<RC_PROCESSModel>();
		}

        public virtual List<RC_PROCESSModel> CreateModelList(ref IQueryable<RC_PROCESS> queryData)
        {

            List<RC_PROCESSModel> modelList = (from r in queryData
                                              select new RC_PROCESSModel
                                              {
													PROCESS_ID = r.PROCESS_ID,
													DETAIL_ID = r.DETAIL_ID,
													CAR_ID = r.CAR_ID,
													MINE_ID = r.MINE_ID,
													MATERIEL_ID = r.MATERIEL_ID,
													SUPPLIER_ID = r.SUPPLIER_ID,
													TRANSPORT_ID = r.TRANSPORT_ID,
													STATUS = r.STATUS,
													OVERLOAD_RADOM = r.OVERLOAD_RADOM,
													UPDATE_TIME = r.UPDATE_TIME,
          
                                              }).ToList();

            return modelList;
        }

        public virtual bool Create(ref ValidationErrors errors, RC_PROCESSModel model)
        {
            try
            {
                RC_PROCESS entity = m_Rep.GetById(model.PROCESS_ID);
                if (entity != null)
                {
                    errors.Add(Resource.PrimaryRepeat);
                    return false;
                }
                entity = new RC_PROCESS();
               				entity.PROCESS_ID = model.PROCESS_ID;
				entity.DETAIL_ID = model.DETAIL_ID;
				entity.CAR_ID = model.CAR_ID;
				entity.MINE_ID = model.MINE_ID;
				entity.MATERIEL_ID = model.MATERIEL_ID;
				entity.SUPPLIER_ID = model.SUPPLIER_ID;
				entity.TRANSPORT_ID = model.TRANSPORT_ID;
				entity.STATUS = model.STATUS;
				entity.OVERLOAD_RADOM = model.OVERLOAD_RADOM;
				entity.UPDATE_TIME = model.UPDATE_TIME;
  

                if (m_Rep.Create(entity))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.InsertFail);
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

		
		 public virtual bool Deletes(ref ValidationErrors errors,Expression<Func<RC_PROCESS, bool>> whereLambda)
         {
		        try
				{
					using (DBContainer db = new DBContainer())
					{
				
							foreach (var entity in db.RC_PROCESS.Where(whereLambda))
							{
								db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
							}

							if(db.SaveChanges()>0)
							{
								return true;
							}
							else
							{
								return false;
							}
			
					}
				}
				catch (Exception ex)
				{
					errors.Add(ex.Message);
					ExceptionHander.WriteException(ex);
					return false;
				}
        }

         public virtual bool Delete(ref ValidationErrors errors, object id)
        {
            try
            {
                if (m_Rep.Delete(id) == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Delete(ref ValidationErrors errors, object[] deleteCollection)
        {
            try
            {
                if (deleteCollection != null)
                {
                    using (TransactionScope transactionScope = new TransactionScope())
                    {
                        if (m_Rep.Delete(deleteCollection) == deleteCollection.Length)
                        {
                            transactionScope.Complete();
                            return true;
                        }
                        else
                        {
                            Transaction.Current.Rollback();
                            return false;
                        }
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

		
       

        public virtual bool Edit(ref ValidationErrors errors, RC_PROCESSModel model)
        {
            try
            {
                RC_PROCESS entity = m_Rep.GetById(model.PROCESS_ID);
                if (entity == null)
                {
                    errors.Add(Resource.Disable);
                    return false;
                }
                              				entity.PROCESS_ID = model.PROCESS_ID;
				entity.DETAIL_ID = model.DETAIL_ID;
				entity.CAR_ID = model.CAR_ID;
				entity.MINE_ID = model.MINE_ID;
				entity.MATERIEL_ID = model.MATERIEL_ID;
				entity.SUPPLIER_ID = model.SUPPLIER_ID;
				entity.TRANSPORT_ID = model.TRANSPORT_ID;
				entity.STATUS = model.STATUS;
				entity.OVERLOAD_RADOM = model.OVERLOAD_RADOM;
				entity.UPDATE_TIME = model.UPDATE_TIME;
 


                if (m_Rep.Edit(entity))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.NoDataChange);
                    return false;
                }

            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool ChangeSupplier(ref ValidationErrors errors, RC_PROCESSModel model, string userid)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    var cmd = db.Database.Connection.CreateCommand();
                    OracleParameter[] parameters = new OracleParameter[]{
                        new OracleParameter(":P_PROCESSID",OracleDbType.NVarchar2),
                        new OracleParameter(":P_DATE",OracleDbType.NVarchar2),
                        new OracleParameter(":P_MINE",OracleDbType.NVarchar2),
                        new OracleParameter(":P_MATERIEL",OracleDbType.NVarchar2),
                        new OracleParameter(":P_SUPPLIERID",OracleDbType.NVarchar2),
                        new OracleParameter(":P_TRANSPORTID",OracleDbType.NVarchar2),
                        new OracleParameter(":P_USER",OracleDbType.NVarchar2),
                        new OracleParameter(":O_ERRORCODE",OracleDbType.Decimal,ParameterDirection.Output)
                    };
                    parameters[0].Value = model.PROCESS_ID;
                    parameters[1].Value = ((DateTime)model.UPDATE_TIME).ToString("yyyy-MM-dd");
                    parameters[2].Value = model.MINE_ID;
                    parameters[3].Value = model.MATERIEL_ID;
                    parameters[4].Value = model.SUPPLIER_ID;
                    parameters[5].Value = model.TRANSPORT_ID;
                    parameters[6].Value = userid;
                    parameters[7].Value = 0;

                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "PCK_CARWEIGHT.UPDATE_BATCHINFO";
                    cmd.Parameters.AddRange(parameters);
                    cmd.Connection.Open();
                    cmd.ExecuteNonQuery();
                    cmd.Connection.Close();
                    string result = parameters[7].Value.ToString();
                    if (result == "0")
                    {
                        return true;
                    }
                    else
                    {
                        switch (result)
                        {
                            case "-20012":
                                errors.Add("参数有误，无法获取ProcessId对应验票记录！");
                                break;
                            case "-20011":
                                errors.Add("输入物料有误，无法获取物料类型！建议维护物料信息再进行此操作！");
                                break;
                            case "-20013":
                                errors.Add("输入参数有误，无法获取目标参数对应调运计划！");
                                break;
                            default:
                                errors.Add(Resource.NoDataChange);
                                break;

                        }
                        return false;
                    }
                }

            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }



        public virtual RC_PROCESSModel GetById(object id)
        {
            if (IsExists(id))
            {
                RC_PROCESS entity = m_Rep.GetById(id);
                RC_PROCESSModel model = new RC_PROCESSModel();
                              				model.PROCESS_ID = entity.PROCESS_ID;
				model.DETAIL_ID = entity.DETAIL_ID;
				model.CAR_ID = entity.CAR_ID;
				model.MINE_ID = entity.MINE_ID;
				model.MATERIEL_ID = entity.MATERIEL_ID;
				model.SUPPLIER_ID = entity.SUPPLIER_ID;
				model.TRANSPORT_ID = entity.TRANSPORT_ID;
				model.STATUS = entity.STATUS;
				model.OVERLOAD_RADOM = entity.OVERLOAD_RADOM;
				model.UPDATE_TIME = entity.UPDATE_TIME;
 
                return model;
            }
            else
            {
                return null;
            }
        }

		public virtual RC_PROCESSModel GetItem(Expression<Func<RC_PROCESS, bool>> whereLambda)
        {
 
                RC_PROCESS entity = m_Rep.GetItem(whereLambda);
                if (entity == null) return null;

                RC_PROCESSModel model = new RC_PROCESSModel();
                              				model.PROCESS_ID = entity.PROCESS_ID;
				model.DETAIL_ID = entity.DETAIL_ID;
				model.CAR_ID = entity.CAR_ID;
				model.MINE_ID = entity.MINE_ID;
				model.MATERIEL_ID = entity.MATERIEL_ID;
				model.SUPPLIER_ID = entity.SUPPLIER_ID;
				model.TRANSPORT_ID = entity.TRANSPORT_ID;
				model.STATUS = entity.STATUS;
				model.OVERLOAD_RADOM = entity.OVERLOAD_RADOM;
				model.UPDATE_TIME = entity.UPDATE_TIME;
 
                return model; 
        }


		 /// <summary>
        /// 校验Excel数据,这个方法一般用于重写校验逻辑
        /// </summary>
        public virtual bool CheckImportData(string fileName, List<RC_PROCESSModel> list,ref ValidationErrors errors )
        {
          
            var targetFile = new FileInfo(fileName);

            if (!targetFile.Exists)
            {

                errors.Add("导入的数据文件不存在");
                return false;
            }

            var excelFile = new ExcelQueryFactory(fileName);

            //对应列头
			 				 excelFile.AddMapping<RC_PROCESSModel>(x => x.PROCESS_ID, "PROCESS_ID");
				 excelFile.AddMapping<RC_PROCESSModel>(x => x.DETAIL_ID, "DETAIL_ID");
				 excelFile.AddMapping<RC_PROCESSModel>(x => x.CAR_ID, "CAR_ID");
				 excelFile.AddMapping<RC_PROCESSModel>(x => x.MINE_ID, "MINE_ID");
				 excelFile.AddMapping<RC_PROCESSModel>(x => x.MATERIEL_ID, "MATERIEL_ID");
				 excelFile.AddMapping<RC_PROCESSModel>(x => x.SUPPLIER_ID, "SUPPLIER_ID");
				 excelFile.AddMapping<RC_PROCESSModel>(x => x.TRANSPORT_ID, "TRANSPORT_ID");
				 excelFile.AddMapping<RC_PROCESSModel>(x => x.STATUS, "STATUS");
				 excelFile.AddMapping<RC_PROCESSModel>(x => x.OVERLOAD_RADOM, "OVERLOAD_RADOM");
				 excelFile.AddMapping<RC_PROCESSModel>(x => x.UPDATE_TIME, "UPDATE_TIME");
 
            //SheetName
            var excelContent = excelFile.Worksheet<RC_PROCESSModel>(0);
            int rowIndex = 1;
            //检查数据正确性
            foreach (var row in excelContent)
            {
                var errorMessage = new StringBuilder();
                var entity = new RC_PROCESSModel();
						 				  entity.PROCESS_ID = row.PROCESS_ID;
				  entity.DETAIL_ID = row.DETAIL_ID;
				  entity.CAR_ID = row.CAR_ID;
				  entity.MINE_ID = row.MINE_ID;
				  entity.MATERIEL_ID = row.MATERIEL_ID;
				  entity.SUPPLIER_ID = row.SUPPLIER_ID;
				  entity.TRANSPORT_ID = row.TRANSPORT_ID;
				  entity.STATUS = row.STATUS;
				  entity.OVERLOAD_RADOM = row.OVERLOAD_RADOM;
				  entity.UPDATE_TIME = row.UPDATE_TIME;
 
                //=============================================================================
                if (errorMessage.Length > 0)
                {
                    errors.Add(string.Format(
                        "第 {0} 列发现错误：{1}{2}",
                        rowIndex,
                        errorMessage,
                        "<br/>"));
                }
                list.Add(entity);
                rowIndex += 1;
            }
            if (errors.Count > 0)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        public virtual void SaveImportData(IEnumerable<RC_PROCESSModel> list)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    foreach (var model in list)
                    {
                        RC_PROCESS entity = new RC_PROCESS();
                       						entity.PROCESS_ID = model.PROCESS_ID;
						entity.DETAIL_ID = model.DETAIL_ID;
						entity.CAR_ID = model.CAR_ID;
						entity.MINE_ID = model.MINE_ID;
						entity.MATERIEL_ID = model.MATERIEL_ID;
						entity.SUPPLIER_ID = model.SUPPLIER_ID;
						entity.TRANSPORT_ID = model.TRANSPORT_ID;
						entity.STATUS = model.STATUS;
						entity.OVERLOAD_RADOM = model.OVERLOAD_RADOM;
						entity.UPDATE_TIME = model.UPDATE_TIME;
 
                        db.RC_PROCESS.Add(entity);
                    }
                    db.SaveChanges();
                }
            }
            catch
            {
                throw;
            }
        }


        public virtual bool IsExists(object id)
        {
            return m_Rep.IsExist(id);
        }
		  public void Dispose()
        { 
            
        }

	}
}
